/**
* File Name: pthread_shared.c
* Auther: Jichang
* Environment: Fedora 7 server
* test main and child-thread about mutex.
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<pthread.h>

// define a mutex
pthread_mutex_t mutex;

void *tfn(void *arg)
{
	srand(time(NULL));

	while(1) {
		// Lock
		pthread_mutex_lock(&mutex);

		printf("hello ");
		// simulate share resource in long time
		// result CUP change,and wrong with time.
		sleep(rand() % 1);
		printf("world\n");

		// Unlock
		pthread_mutex_unlock(&mutex);

		sleep(rand() % 1);
	}
	return NULL;
}

int main(int argc, char *argv[])
{
	pthread_t tid;
	srand(time(NULL));

	// init mutex before create.
	int ret = pthread_mutex_init(&mutex, NULL);
	if(ret != 0) {
		fprintf(stderr, "mutex init error: %s\n", strerror(ret));
		exit(1);
	}

	pthread_create(&tid, NULL, tfn, NULL);
	while(1) {
		// Lock mutex--
		pthread_mutex_lock(&mutex);

		printf("HELLO ");
		sleep(rand() % 1);
		printf("WORLD\n");

		// Unlock mutex++
		pthread_mutex_unlock(&mutex);

		sleep(rand() % 1);
	}
	pthread_join(tid, NULL);

	// destroy mutex.
	pthread_mutex_destroy(&mutex);
	
	return 0;
}

